package net.atos.hibernate_spring;

import static org.junit.Assert.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = { "classpath:/META-INF/spring/app-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class BookPersistenceWithJDBC {

    @Value("#{dataSource}")
    private DataSource dataSource;

    @Test
    public void readingWithJDBC() throws SQLException {

	final Connection connection = dataSource.getConnection();
	final Statement statement = connection.createStatement();
	final String query = "SELECT * FROM Book WHERE id = 1";
	final ResultSet result = statement.executeQuery(query);
	final List<Book> books = new ArrayList<Book>();
	while (result.next()) {
	    final Book book = new Book(result.getString("title"), result.getString("name"));
	    books.add(book);
	}
	final Book book = books.get(0);

	assertEquals(1, books.size());
	assertEquals("Trylogia, czesc I", book.getTitle());
	assertEquals("Sienkiewicz", book.getName());
    }

}
